package com.atguigu.spzx.manager.controller;


import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Tag(name = "商品分类管理") //用于描述类的作用
@RestController
@RequestMapping("/admin/product/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;


    @Operation(summary = "导入接口")
    @PostMapping("importData")
    public Result importData(MultipartFile file){
        categoryService.importData(file);
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }


    //文件的导出下载
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {

        //文件下载时，设置了三个请求头
        //1、响应内容的类型（下载的数据的类型）excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //2、响应头设置响应编码
        response.setCharacterEncoding("utf-8");
        //3、Content-disposition，设置下载文件的附件名
        //对中文文件名进行编码，防止中文乱码
        String fileName = URLEncoder.encode("全部商品分类", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        //4、从数据库查询所有的分类  List<Category> ，转成 List<CategoryExcelVo>
        List<Category> categoryList = categoryService.findAll();
        //5、将Category转成CategoryExcelVo
        List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>();
        categoryList.forEach(category -> {
            CategoryExcelVo excelVo = new CategoryExcelVo();
            //将category中的属性拷贝到excelVo中，只能拷贝相同名称的属性 id==>id(√)     name => aName(X)
            BeanUtils.copyProperties(category,excelVo);//spring中的工具类
            categoryExcelVoList.add(excelVo);
        });

        //6、调用easyexcel的api方法
        EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                .sheet("全部商品分类")
                .doWrite(categoryExcelVoList);
    }

    @Operation(summary = "查询分类列表，并且统计该分类是否存在下级")
    @GetMapping("findByParentId/{parentId}")
    public Result findByParentId(@PathVariable Long parentId){
        List<Category> list = categoryService.findByParentId(parentId);
        return Result.build(list, ResultCodeEnum.SUCCESS);
    }

}